import { Modal, ModalProps } from 'antd';
import { FC, useRef, useState } from 'react';
import Draggable, { DraggableData, DraggableEvent } from 'react-draggable';

interface DraggableModalProps extends Omit<ModalProps, 'modalRender'> {
  title: string;
}

export const DraggableModal: FC<DraggableModalProps> = ({
  title,
  children,
  ...modalProps
}) => {
  const draggableRef = useRef<HTMLDivElement>();
  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });

  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggableRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  return (
    <Modal
      {...modalProps}
      getContainer={() => document.getElementById('app-cad_root')}
      title={
        <div
          className='w-full cursor-move select-none'
          onMouseOver={() => {
            if (disabled) {
              setDisabled(false);
            }
          }}
          onMouseOut={() => {
            setDisabled(true);
          }}
        >
          {title}
        </div>
      }
      modalRender={(modal) => (
        <Draggable
          disabled={disabled}
          bounds={bounds}
          nodeRef={draggableRef}
          onStart={onStart}
        >
          <div ref={draggableRef}>{modal}</div>
        </Draggable>
      )}
    >
      {children}
    </Modal>
  );
};
